import org.w3c.dom.css.Counter;

import java.util.concurrent.locks.ReentrantLock;

public class Demo_1104 {
    public static void main(String[] args) throws InterruptedException{
        Counter1104 counter = new Counter1104();

        //创建两个线程对一个变量进行累加
        Thread t1 = new Thread(()->{
            //5万次
            for (int i=0;i<50000;i++){
                counter.increase();
            }
        });

        //线程2
        Thread t2 = new Thread(()->{
            for (int i=0;i<50000;i++)
                counter.increase();
        });

        //启动线程
        t1.start();
        t2.start();

        //等待线程完成
        t1.join();
        t2.join();

        //查看运行结果
        System.out.println("count = "+ counter.count);  //count = 100000
    }
}


class Counter1104{
    //多线程环境中修改变量加volatile
    public volatile int count = 0;

    //初始化一把锁
    ReentrantLock lock = new ReentrantLock();

    public void increase(){
        try {
            //上锁
            lock.lock();
            count++;
        }finally {
            //释放锁
            lock.unlock();
        }
    }
}
